package com.zhixing.map.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.zhixing.common.domain.dto.RoutePlanningDTO;
import com.zhixing.common.domain.vo.RoutePlanningVO;
import com.zhixing.common.exception.ZhixingException;
import com.zhixing.map.service.MapService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

import static com.zhixing.common.domain.enums.HttpStatus.ROUTE_PLANNING_FAIL;

@Service
@RequiredArgsConstructor
public class MapServiceImpl implements MapService {

    @Value("${tencent.key}")
    private String key;

    private final RestTemplate restTemplate;

    @Override
    public RoutePlanningVO routePlanning(RoutePlanningDTO routePlanningDTO) {
        // 腾讯地图路线规划
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from=" + routePlanningDTO.getStartLatitude() + "," + routePlanningDTO.getStartLongitude()
                + "&to=" + routePlanningDTO.getEndLatitude() + "," + routePlanningDTO.getEndLongitude() + "&key=" + key;
        JSONObject result = restTemplate.getForObject(url, JSONObject.class);
        if (ObjectUtil.isEmpty(result) || Objects.requireNonNull(result).getIntValue("status") != 0) throw new ZhixingException(ROUTE_PLANNING_FAIL);
        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        return new RoutePlanningVO(route.getBigDecimal("distance").divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP),
                route.getInteger("duration"), route.getJSONArray("polyline"));
    }
}
